package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var log *zap.Logger

// Init 初始化日志
func Init(level, encoding, outputPath, errorPath string, initialFields map[string]string) {
	var zapLevel zapcore.Level
	if err := zapLevel.UnmarshalText([]byte(level)); err != nil {
		zapLevel = zap.InfoLevel
	}

	initialFieldsInterface := make(map[string]interface{}, len(initialFields))
	for k, v := range initialFields {
		initialFieldsInterface[k] = v
	}

	cfg := zap.Config{
		Level:            zap.NewAtomicLevelAt(zapLevel),
		Encoding:         encoding,
		OutputPaths:      []string{"stdout", outputPath},
		ErrorOutputPaths: []string{"stderr", errorPath},
		InitialFields:    initialFieldsInterface,
		EncoderConfig: zapcore.EncoderConfig{
			MessageKey:    "message",
			LevelKey:      "level",
			TimeKey:       "time",
			CallerKey:     "caller",
			StacktraceKey: "stacktrace",
			EncodeLevel:   zapcore.CapitalColorLevelEncoder, // 彩色日志输出
			EncodeTime:    zapcore.ISO8601TimeEncoder,       // ISO8601 时间格式
			EncodeCaller:  zapcore.ShortCallerEncoder,       // 短路径调用者
		},
	}

	var err error
	log, err = cfg.Build()
	if err != nil {
		panic("failed to initialize logger: " + err.Error())
	}

	zap.ReplaceGlobals(log) // 设置为全局 Zap logger
}

// L 获取全局 Zap logger 实例
func L() *zap.Logger {
	return log
}
